﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using LostLib;
using LostLib.Win32;
using System.Diagnostics;

namespace LostLib.Windows
{
	class WindowsManager
	{
		static void Main(string[] args)
		{
			if (args.Length == 0)
			{
				var consoleWindow = ScreenWindow.GetConsoleWindow( );
				Application.EnableVisualStyles( );
				Application.SetCompatibleTextRenderingDefault(false);
				consoleWindow.Hide( );
				Application.Run(new WindowsManagerWindow( ));
				return;
			}

			switch (args[0])
			{
			case "mouse-restrict":
				MouseRestrict(args.Skip(1));
				return;
			case "gui":
				var consoleWindow = ScreenWindow.GetConsoleWindow( );
				Application.EnableVisualStyles( );
				Application.SetCompatibleTextRenderingDefault(false);
				consoleWindow.Hide( );
				Application.Run(new WindowsManagerWindow( ));
				return;
			case "console":
				throw new NotImplementedException( );
			case "gui+console":
				Application.EnableVisualStyles( );
				Application.SetCompatibleTextRenderingDefault(false);
				Application.Run(new WindowsManagerWindow( ));
				break;
			default:
				throw new InvalidOperationException(args[0]);
			}
		}

		private static void MouseRestrict(IEnumerable<string> args)
		{
			string className = null;
			string title = null;

			var enumerator = args.GetEnumerator( );
			while (enumerator.MoveNext( ))
			{
				switch (enumerator.Current)
				{
				case "-class":
					className = enumerator.GetNext( );
					break;
				case "-title":
					title = enumerator.GetNext( );
					break;
				default:
					throw new ArgumentException(enumerator.Current);
				}
			}

			if ((className ?? title) == null)
				Mouse.ClipCursor(null);
			else
			{
				var window = (from wnd in ScreenWindow.Root.GetChilds(true)
							  where
								 ((className == null) || (className == wnd.ClassName))
								 && ((title == null) || (title == wnd.Text))
							  select wnd).First( );
				Mouse.ClipCursor(
					new Rect( ) {
						Left = window.ClientLeft,
						Top = window.ClientTop,
						Width = window.ClientWidth,
						Height = window.ClientHeight,
					});
			}
		}
	}
}
